const gulp = require("gulp");
// 刷新浏览器
const connect = require("gulp-connect");
// 压缩页面
const htmlmin = require("gulp-htmlmin");
// 压缩js
const uglify = require("gulp-uglify");
// 压缩css
const cssmin = require("gulp-cssmin");
// js转义，ES6=>ES5
const babel = require("gulp-babel");
// css转义
const sass = require("gulp-sass")(require("sass"));

// 测试指令
gulp.task("sayhi",async()=>{
    console.log("hello gulp");
})
// 刷新浏览器
gulp.task("connect",async()=>{
    connect.server({
        livereload:true
    })
})
// 转存src里面的所有html页面指令
gulp.task("html",async()=>{
    // 源文件路径
    gulp.src(["./src/**/*.html"])
    // 目标文件路径
    .pipe(gulp.dest("./dist"))
    // 文件存至目标路径后刷新浏览器
    .pipe(connect.reload())
})
// 页面压缩
gulp.task("html-min",async()=>{
    gulp.src(["./src/**/*html"])
    .pipe(htmlmin({collapseWhitespace:true}))
    .pipe(gulp.dest("./dist"))
    .pipe(connect.reload());
})
// js转存
gulp.task("javascripts",async()=>{
    gulp.src(["./src/javascripts/**/*.js"])
    .pipe(gulp.dest("./dist/javascripts"))
    .pipe(connect.reload());
})
// js压缩
gulp.task("javascripts-min",async()=>{
    gulp.src(["./src/javascripts/**/*.js"])
    .pipe(uglify())
    .pipe(gulp.dest("./dist/javascripts"))
    .pipe(connect.reload());
})
// js转义
gulp.task("javascripts-babel",async()=>{
    gulp.src(["./src/javascripts/**/*.js"])
    .pipe(babel({
        presets:['@babel/env']
    }))
    .pipe(uglify())
    .pipe(gulp.dest("./dist/javascripts"))
    .pipe(connect.reload());
})
// css转义
gulp.task("scss",async()=>{
    gulp.src(["./src/scss/**/*.scss"])
    .pipe(sass().on('error',sass.logError))
    .pipe(gulp.dest("./dist/css"))
    .pipe(connect.reload());
})
// css压缩
gulp.task("scss-min",async()=>{
    gulp.src(["./src/scss/**/*.scss"])
    .pipe(sass().on('error',sass.logError))
    .pipe(cssmin())
    .pipe(gulp.dest("./dist/css"))
    .pipe(connect.reload());
})

// 监听
gulp.task("watch",async()=>{
    gulp.watch(["./src/**/*.html"],gulp.parallel("html"));
    gulp.watch(["./src/javascripts/**/*.js"],gulp.parallel("javascripts"));
    gulp.watch(["./src/scss/**/*.scss"],gulp.parallel("scss"));
})

gulp.task("default",gulp.series("html","scss","javascripts",gulp.parallel("connect","watch")));
// 压缩指令
gulp.task("build",gulp.series("html-min","scss-min","javascripts-min"));